package com.kd.spring.unit;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

public class JdbcTemplateTest {
	private static JdbcTemplate jdbcTemplate;

	@BeforeClass
	public static void init() {
		String url = "jdbc:sqlserver://localhost:1433;databaseName=kd_shop";
		String username = "sa";
		String password = "123";
		DriverManagerDataSource dataSource = new DriverManagerDataSource(url,
				username, password);
		dataSource
				.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
		jdbcTemplate = new JdbcTemplate(dataSource);
	}

	@Test
	public void test() {
		// 1.声明SQL
		String sql = "select * from kd_user";
		jdbcTemplate.query(sql, new RowCallbackHandler() {

			@Override
			public void processRow(ResultSet rs) throws SQLException {
				// TODO Auto-generated method stub
				// 2.处理结果集
				String value = rs.getString("username");
				System.out.println("Column username:" + value);
			}
		});
	}

	@Test
	// 配置文件 的连接池
	public void test1() {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
				"springSqlConnect.xml");
		JdbcTemplate jdbcTemplate = (JdbcTemplate) applicationContext.getBean("jdbcTemplate");
		
		String sql = "select * from kd_user";
		
		jdbcTemplate.query(sql, new RowCallbackHandler() {

			@Override
			public void processRow(ResultSet rs) throws SQLException {
				// TODO Auto-generated method stub
				// 2.处理结果集
				String value = rs.getString("username");
				System.out.println("Column username:" + value);
				System.out.println("Column username:" + value);
			}
		});
	}

}
